package com.agri.controller;

import com.agri.dto.CartItemDTO;
import com.agri.result.Result;
import com.agri.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 购物车控制器
 * 提供购物车商品的添加、删除、修改和查询接口
 *
 * @author Agri-Fin-Sale Team
 * @since 2025-11-05
 */
@RestController
@RequestMapping("/cart")
@PreAuthorize("hasRole('USER')")
public class CartController {
    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     */
    @PostMapping("/item")
    public Result<?> addToCart(@Valid @RequestBody CartItemDTO cartItemDTO) {
        return cartService.addToCart(cartItemDTO);
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/item/{itemId}")
    public Result<?> updateCartItem(@PathVariable Long itemId, 
                                   @RequestParam Integer quantity) {
        return cartService.updateCartItem(itemId, quantity);
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/item/{itemId}")
    public Result<?> removeCartItem(@PathVariable Long itemId) {
        return cartService.removeCartItem(itemId);
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public Result<?> clearCart(@RequestParam Long userId) {
        return cartService.clearCart(userId);
    }

    /**
     * 获取用户购物车列表
     */
    @GetMapping("/list")
    public Result<?> getCartList(@RequestParam Long userId) {
        return cartService.getCartList(userId);
    }

    /**
     * 批量删除购物车商品
     */
    @DeleteMapping("/items/batch")
    public Result<?> removeCartItems(@RequestBody List<Long> itemIds) {
        return cartService.removeCartItems(itemIds);
    }

    /**
     * 获取购物车商品数量
     */
    @GetMapping("/count")
    public Result<?> getCartCount(@RequestParam Long userId) {
        return cartService.getCartCount(userId);
    }
}